//
//  LoginViewController.swift
//  TODOApp
//
//  Created by chenyh on 2018/5/30.
//  Copyright © 2018年 chenyh. All rights reserved.
//

import UIKit
import Alamofire

class LoginViewController: UIViewController {

    @IBOutlet weak var usernameTF: UITextField!
    @IBOutlet weak var passwordTF: UITextField!
    
    @IBOutlet weak var regBtn: UIButton!
    @IBOutlet weak var loginBtn: UIButton!
    fileprivate let accountProvider = AccountProvider()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func clickLoginAction(_ sender: Any) {
        guard let username = usernameTF.text else {
            return
        }
        
        guard let password = passwordTF.text else {
            return
        }
        
        guard !username.isEmpty else {
            return
        }
        guard !password.isEmpty else {
            return
        }
        
        
        login(username: username, password: password.sha1())
    }
    @IBAction func clickRegisterAction(_ sender: Any) {
        guard let username = usernameTF.text else {
            return
        }
        
        guard let password = passwordTF.text else {
            return
        }
        
        guard !username.isEmpty else {
            return
        }
        guard !password.isEmpty else {
            return
        }
        
       
        register(username: username, password: password)
    }
    private func register(username: String,password: String) {
        
        let task = Alamofire
            .request("http://0.0.0.0:8888/api/v1/auth/register",
                     method: .post,
                     parameters: ["username": username,"password": password],
                     encoding: JSONEncoding.default,
                     headers: ["Content-Type" : "application/json"])
            .responseJSON(queue: DispatchQueue.global(), options: JSONSerialization.ReadingOptions.mutableContainers) {
           
                if let dict = try? JSONSerialization.jsonObject(with: $0.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                    if dict == nil {
                        return
                    }
                    guard let result = dict!["result"] as? [String: Any] else {
                        return
                    }
                    if let account = Account.deserialize(from: result) {
                        account.archiveObject()
                        DispatchQueue.main.async {
                            AppDelegate.shared.gotoHome()
                        }
                    }
                }
        }
        task.resume()
    }
    
    private func login(username: String,password: String) {
        
        let task = Alamofire
            .request("http://0.0.0.0:8888/api/v1/auth/login",
            method: .post,
            parameters: ["username": username,"password": password],
            encoding: JSONEncoding.default,
            headers: ["Content-Type" : "application/json"])
            .responseJSON(queue: DispatchQueue.global(), options: JSONSerialization.ReadingOptions.mutableContainers) {
              
                
                if let dict = try? JSONSerialization.jsonObject(with: $0.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                    if dict == nil {
                        return
                    }
                    guard let result = dict!["result"] as? [String: Any] else {
                        return
                    }
                    if let account = Account.deserialize(from: result) {
                        account.archiveObject()
                        DispatchQueue.main.async {
                            AppDelegate.shared.gotoHome()
                        }
                    }
                }
        }
        task.resume()

    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
